import numpy as np
import cv2,os

crop_image = lambda img, x0, y0, w, h: img[y0:y0+h, x0:x0+w]

def mkdir(path):
    if(os.path.exists(path)):
        return path
    os.mkdir(path)
    return path

def random_crop(img, area_ratio, hw_variRange):
    h, w = img.shape[:2]
    hw_delta = np.random.uniform(0, hw_variRange)
    hw_mult = 1 + hw_delta
    w_crop = int(round(w*np.sqrt(area_ratio*hw_mult)))
    if w_crop > w - 2:
        w_crop = w - 2
    h_crop = int(round(h*np.sqrt(area_ratio/hw_mult)))
    if h_crop > h - 2:
        h_crop = h - 2
    x0 = np.random.randint(0, w-w_crop-1)
    y0 = np.random.randint(0, h-h_crop-1)
    return crop_image(img, x0, y0, w_crop, h_crop)

def rotate_image(img, angle, crop):#bool:crop
    # angle =  np.random.randint(0-angleVari,angleVari)
    h, w = img.shape[:2]
    angle %= 360
    M_rotate = cv2.getRotationMatrix2D((w/2, h/2), angle, 1)
    img_rotated = cv2.warpAffine(img, M_rotate, (w, h))

    if crop:
        angle_crop = angle % 180
        if angle_crop > 90:
            angle_crop = 180 - angle_crop
        theta = angle_crop * np.pi / 180.0
        hw_ratio = float(h) / float(w)
        tan_theta = np.tan(theta)
        numerator = np.cos(theta) + np.sin(theta) * tan_theta
        r = hw_ratio if h > w else 1 / hw_ratio
        denominator = r * tan_theta + 1
        crop_mult = numerator / denominator
        w_crop = int(round(crop_mult*w))
        h_crop = int(round(crop_mult*h))
        x0 = int((w-w_crop)/2)
        y0 = int((h-h_crop)/2)

        img_rotated = crop_image(img_rotated, x0, y0, w_crop, h_crop)

    return img_rotated

def cropAngle(angle_vari,p_crop=1):
    angle = np.random.uniform(-angle_vari, angle_vari)
    print(" np.random.random=", np.random.random())
    crop = False if np.random.random() > p_crop else True
    print(crop)
    return angle,crop

def random_rotate(img, angle_vari, p_crop=1):
    angle, crop = cropAngle(angle_vari,p_crop)
    return rotate_image(img, angle, crop)

def hsv_transform(img, hue_delta, sat_mult, val_mult):
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(np.float)
    img_hsv[:, :, 0] = (img_hsv[:, :, 0] + hue_delta) % 180
    img_hsv[:, :, 1] *= sat_mult
    img_hsv[:, :, 2] *= val_mult
    img_hsv[img_hsv > 255] = 255
    return cv2.cvtColor(np.round(img_hsv).astype(np.uint8), cv2.COLOR_HSV2BGR)

def random_hsv_transform(img, hue_vari, sat_vari, val_vari):
    hue_delta = np.random.randint(-hue_vari, hue_vari)
    sat_mult = 1 + np.random.uniform(-sat_vari, sat_vari)
    val_mult = 1 + np.random.uniform(-val_vari, val_vari)
    return hsv_transform(img, hue_delta, sat_mult, val_mult)

def gamma_transform(img, gamma):
    gamma_table = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)]
    gamma_table = np.round(np.array(gamma_table)).astype(np.uint8)
    return cv2.LUT(img, gamma_table)

def random_gamma_transform(img, gamma_vari=0.8):
    log_gamma_vari = np.log(gamma_vari)
    print("log",log_gamma_vari)
    alpha = np.random.uniform(-log_gamma_vari, log_gamma_vari)
    gamma = np.exp(alpha)
    print("gamma",gamma)
    return gamma_transform(img, gamma)

def flip(img,model):
    xImg = cv2.flip(img, model, dst=None)  # model: 水平镜像1,垂直镜像0,对角镜像-1
    # xImg1 = cv.flip(img, model, dst=None)  # 垂直镜像
    # xImg2 = cv.flip(img, model, dst=None)  # 对角镜像
    return xImg

def random_flip(img,model,falseModel=None):
    if(model == "auto"):
        model = np.random.randint(-1,2)
    if(falseModel!=None):
        if(falseModel==model):
            return img
    fImg = flip(img,model)

    return fImg

def resizeImg(w,h,img):
    return cv2.resize(img,(w,h))

def random_resizeImg(limitW,limitH,img):
    _,w,h = img.shape[::-1]
    minW,minH = limitW[0],limitH[0]
    maxW,maxH = limitW[1],limitH[1]

    if(minW<w<maxW and minH<h<maxH):
        return img

    else:
        if(w<h):
            rh = np.random.randint(minH, maxH)
            rw = int(rh / (1.0 * h) * w)
        else:
            rw = np.random.randint(minW, maxW)
            rh = int(rw / (w * 1.0) * h)

    if(rw<minW ):
        rw = np.random.randint(minW, maxW)



    # if(not(minW<w<maxW)):
    #     if(w<minW):
    #         rw = np.random.randint(minW,maxW)
    #         rh = int(rw/(w*1.0)*h)
    #     else:
    #         rw = np.random.randint(maxW,min(int(maxW*1.3),w) )
    #         rh = int(rw / (w * 1.0) * h)
    #
    # if(not(minH<h<maxH)):


    # else:
    #     rh = np.random.randint(h,maxH)
    #     rw = int(rh/(1.0*h)*h)

    # if()

    return resizeImg(rw,rh,img)

def Agu():
    skip = []
    # with open("/mnt/data/Pyproject/clothesTrainData/labelPaths/test/list.list",'r') as f:
    #     lines = f.readlines()
    #     for line in lines:
    #         line = line.replace("--",'')
    #         line = line.rstrip().split("/")[-1]
    #         skip.append(line)

    path ="/mnt/data/people/falldown"
    limitW, limitH = [300,500],[300,500]
    for file  in os.listdir(path):
        if(file.endswith(".txt")):
            continue
        # if(file.split('.')[0] in skip):
        #     continue
        # if(file!="360农村晒衣服2_00001200.jpg"):
        #     continue
        imgPath = os.path.join(path,file)
        # imgPath = "/mnt/data/Pyproject/clothesTrainData/labelPaths/1/360农村晒衣服2_00001900.jpg"
        name = imgPath.split("/")[-1].split(".")[0]
        img = cv2.imread(imgPath)
        print(img.shape[::-1][1:])
        dst = os.path.join("/mnt/data/people/falldown_auto",name)
        mkdir(dst)
        for i in range(10):
            result = img
            # result = random_hsv_transform(result, 80,0.1, 0.20)
            result = random_hsv_transform(result, 30,0.1, 0.20)
            result = random_rotate(result, 15)

            result = random_gamma_transform(result,0.8)
            # result = random_gamma_transform(result,1.7)

            # result=random_flip(result,"auto",1)#model: 水平镜像1,垂直镜像0,对角镜像-1
            # result=random_flip(result,"auto",-1)#model: 水平镜像1,垂直镜像0,对角镜像-1
            ifFlip = np.random.randint(0, 2)
            if(ifFlip==0):
                result=random_flip(result,1)#model: 水平镜像1,垂直镜像0,对角镜像-1
            # result = random_resizeImg(limitW,limitH,result)
            _,w,h = result.shape[::-1]
            randomSize = np.random.randint(8, 13)/10.0
            result = resizeImg(int(w*randomSize),int(h*randomSize),result)

            cv2.imwrite(os.path.join(dst,name+"_"+str(i)+".png"), result)
            print(result.shape[::-1][1:])
            # cv2.imshow(name,result)
            # cv2.waitKey(1000)

def main():
    Agu()

if __name__ == "__main__":
    main()